import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { ChatSessionResponse } from "@/types";
import {getSessionList} from "@/api/session";

export const useChatSessionStore = defineStore("chatSession", () => {
  // ==============================状态========================================
  // 会话列表
  const sessions = ref<ChatSessionResponse[]>([]);

  // 当前选中的会话ID
  const currentSessionId = ref<string | null>(null);

  // 加载状态
  const loading = ref(false);

  // ==============================计算属性========================================
  // 当前选中的会话
  const currentSession = computed(() =>
    sessions.value.find((s) => s.id === currentSessionId.value)
  );

  /**
   * 排序后的会话列表
   * 1. 置顶的会话优先显示
   * 2. 按最后消息时间倒序排列
   */
  const sortedSessions = computed(() => {
    return [...sessions.value].sort((a, b) => {
      // 优先按置顶状态排序
      if (a.isTop !== b.isTop) {
        return b.isTop ? 1 : -1;
      }
      // 其次按最后消息时间排序
      const timeA = a.lastMessageTime
        ? new Date(a.lastMessageTime).getTime()
        : 0;
      const timeB = b.lastMessageTime
        ? new Date(b.lastMessageTime).getTime()
        : 0;
      return timeB - timeA;
    });
  });

  /**
   * 根据targetId获取会话
   * @param targetId 目标ID
   * @returns 会话
   */
  const getSessionByTargetId = (targetId: string) => {
    return sessions.value.find((s) => s.targetId === targetId);
  };

  /**
   * 插入会话
   * @param session 会话
   */
  const insertSession = (session: ChatSessionResponse) => {
    sessions.value.push(session);
  };

  /**
   * 所有会话未读消息总数
   */
  const totalUnread = computed(() =>
    sessions.value.reduce((sum, session) => sum + session.unreadCount, 0)
  );

  // ==============================方法========================================
  /**
   * 加载会话列表
   */
  const loadSessions = async () => {
    loading.value = true;
    try {
      const { data } = await getSessionList();
      sessions.value = data;
    } catch (error) {
      console.error("Failed to load sessions:", error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 更新会话最后一条消息
   * @param sessionId 会话ID
   * @param message 消息内容
   */
  const updateLastMessage = (sessionId: string, message: string) => {
    const session = sessions.value.find((s) => s.id === sessionId);
    if (session) {
      session.lastMessage = message;
      session.lastMessageTime = new Date().toISOString();
    }
  };

  

  return {
    // 状态
    sessions,
    currentSessionId,
    loading,
    // 计算属性
    currentSession,
    sortedSessions,
    totalUnread,
    // 方法
    loadSessions,
    updateLastMessage,
    getSessionByTargetId,
    insertSession
  };
});
